<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-07 14:14:53
 * @LastEditors: your name
 * @LastEditTime: 2021-05-10 16:11:39
 * @Description: file content
-->
<route>
{
  "meta":{
    "title": "用户组",
    "showMenu" :true,
    "serialNum": 30,
    "localism": "sys.user_group"
  }
}
</route>
<template>
  <div style="height: calc(100% - 20px)">
    <el-row :gutter="24" class="pht100">
      <el-col
        :span="4"
        class="pht100 ovya ovhx"
        style="border-right: 1px solid #dcdfe6"
      >
        <ResizableGrid :handleStyle="{ transform: 'translateX(14px)' }">
          <el-tree
            ref="tree"
            class="custom-tree custom-tree--highlight-current"
            :data="groupTree"
            :expand-on-click-node="false"
            node-key="id"
            highlight-current
            :default-expanded-keys="expandedGroup"
            :current-node-key="currentGroup.id"
            @node-click="handleGroupClick"
            @node-expand="handleGroupExpand"
            @node-collapse="handleGroupCollapse"
          >
            <span class="custom-tree__node" slot-scope="{ node, data }">
              <span :title="data.name" class="custom-tree__span">{{
                data.name
              }}</span>
              <el-dropdown
                placement="bottom"
                @command="handleGroupCommand($event, data)"
              >
                <i class="el-icon-more" />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="create" icon="el-icon-plus">{{
                    $t("sys.new_sub_user_group")
                  }}</el-dropdown-item>
                  <el-dropdown-item
                    :disabled="data.isRoot"
                    command="edit"
                    icon="el-icon-edit"
                    >{{ $t("sys.edit_user_group") }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="data.isRoot"
                    command="delete"
                    icon="el-icon-delete"
                    >{{ $t("sys.delete_user_group")
                    }}{{ node.parentId }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    divided
                    :disabled="data.isRoot || data._isFirst"
                    command="up"
                    icon="el-icon-arrow-up"
                    >{{ $t("sys.move_up") }}</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="data.isRoot || data._isLast"
                    command="down"
                    icon="el-icon-arrow-down"
                    >{{ $t("sys.move_down") }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </el-tree>
        </ResizableGrid>
      </el-col>

      <el-col :span="20" class="pht100 ovya" v-if="currentGroup.id">
        <div v-if="!currentGroup.isRoot" style="text-align: end">
          <el-button
            v-if="!isEditDataPermission"
            type="primary"
            icon="el-icon-edit"
            @click="isEditDataPermission = true"
            >{{ $t("sys.edit") }}</el-button
          >
        </div>
        <template v-if="!isEditDataPermission">
          <template v-if="!currentGroup.isRoot">
            <el-row class="setting-item">
              <el-col :span="3">
                <span class="setting-name">{{ $t("sys.administrators") }}</span>
              </el-col>
              <el-col :span="20">
                <el-tag
                  class="role-name-tag"
                  size="medium"
                  closable
                  v-for="item in groupManagers"
                  :key="item.id"
                  type="info"
                  @close="handleGroupManagerDelete(item)"
                  >{{ item.name }}</el-tag
                >
                <i class="el-icon-plus" @click="handleGroupManagerAdd"></i>
              </el-col>
            </el-row>

            <el-row class="setting-item">
              <el-col :span="3">
                <span class="setting-name">{{ $t("sys.member") }}</span>
              </el-col>
              <el-col :span="20">
                <el-tag
                  class="role-name-tag"
                  size="medium"
                  closable
                  v-for="item in groupMembers"
                  :key="item.id"
                  type="info"
                  @close="handleGroupMemberDelete(item)"
                  ><i v-if="item.isOrg" class="el-icon-folder-opened mr5"></i
                  >{{ item.name }}</el-tag
                >
                <i class="el-icon-plus" @click="handleGroupMemberAdd"></i>
              </el-col>
            </el-row>
          </template>

          <el-row class="setting-item">
            <el-col :span="3">
              <span class="setting-name">{{ $t("sys.role") }}</span>
            </el-col>
            <el-col :span="20">
              <span v-if="currentGroup.isRoot">{{ $t("sys.all_roles") }}</span>
              <template v-else>
                <el-tag
                  class="role-name-tag"
                  size="medium"
                  closable
                  v-for="item in groupRoles"
                  :key="item.id"
                  type="info"
                  @close="handleGroupRoleDelete(item)"
                  >{{ item.name }}</el-tag
                >
                <i class="el-icon-plus" @click="handleGroupRoleAdd"></i>
              </template>
            </el-col>
          </el-row>
        </template>
        <template v-if="!currentGroup.isRoot && isEditDataPermission">
          <el-row type="flex" justify="space-between" align="middle">
            <span style="font-size: 18px; font-weight: bold">
              {{ $t("sys.data_permission_configuration") }}
              <el-tooltip
                popper-class="custom-popper"
                :content="$t('sys.not_set_not_view_content')"
                placement="top"
              >
                <!--              <i class="el-icon-question" />-->
              </el-tooltip>
            </span>

            <el-button
              type="primary"
              icon="el-icon-arrow-left"
              @click="isEditDataPermission = false"
              >{{ $t("sys.return") }}</el-button
            >
          </el-row>
          <RangeList
            :group="currentGroup"
            :title="$t('sys.business_model')"
            type="1"
            module-type="DATA_VISIBILITY_PERM_COMPONENT"
          />
        </template>
      </el-col>

      <group-form
        ref="groupForm"
        :treeData="groupTree"
        :defaultConfig="defaultConfig"
        @ok="loadGroupData"
      />

      <role-form ref="roleForm" @ok="loadGroupRole" />

      <select-modal
        :title="$t('sys.select_administrator')"
        ref="SelectManagerModal"
        :treeData="orgTree"
        :disabledNodeKeys="disabledNodeKeys"
        :treeNodeChange="handleSelectManagerNodeChange"
        @ok="handleManagerChange"
      >
        <template v-slot:item="slotProps">
          {{ [slotProps.data.jobNumber, slotProps.data.name] | user }}
        </template>
      </select-modal>

      <select-modal
        :title="$t('sys.select_member')"
        ref="SelectMemberModal"
        :treeData="orgTree"
        showCheckbox
        childDisable
        :disabledNodeKeys="
          groupMembers.filter((m) => m.isOrg === 1).map((item) => item.unionId)
        "
        :treeNodeChange="handleSelectMemberNodeChange"
        @ok="handleMemberChange"
      >
        <template v-slot:node="slotProps">
          {{ slotProps.data.name }}
        </template>
        <template v-slot:item="slotProps">
          {{ [slotProps.data.jobNumber, slotProps.data.name] | user }}
        </template>
      </select-modal>
    </el-row>
  </div>
</template>

<script>
import i18n from "../../../../i18n";
import { Confirm } from "@/utils/decorator";
import { arrayToTree, treeToTree } from "@/utils/util";

import {
  getHmusergroupList,
  putHmusergroupUp,
  putHmusergroupDown,
  deleteHmusergroup,
} from "@/apis/paas/HmUserGroupController.js";
import {
  getHmusergrouproleList,
  deleteHmusergrouprole,
} from "@/apis/paas/HmUserGroupRoleController.js";
import {
  getHmusergroupmanageList,
  deleteHmusergroupmanage,
  postHmusergroupmanage,
} from "@/apis/paas/HmUserGroupManageController.js";
import {
  getHmusergroupmemberList,
  deleteHmusergroupmember,
  postHmusergroupmember,
} from "@/apis/paas/HmUserGroupMemberController.js";
import { getHmorgListwithpermission } from "@/apis/paas/HmOrgController.js";
import { getHmuserPageListwithpermission } from "@/apis/paas/HmUserController.js";

import GroupForm from "./__components__/GroupForm";
import RoleForm from "./__components__/RoleForm";
import RangeList from "./__components__/RangeList";
import SelectModal from "@/components/SelectModal";
import ResizableGrid from "@/components/ResizableGrid";

const defaultConfig = {
  root: 0,
};

export default {
  name: "Group",
  components: {
    GroupForm,
    RoleForm,
    RangeList,
    SelectModal,
    ResizableGrid,
  },
  data() {
    return {
      defaultConfig,
      groupList: [],
      groupTree: [],
      expandedGroup: [],
      currentGroup: {},
      loading: false,
      groupRoles: [],
      groupManagers: [],
      groupMembers: [],
      orgTree: [],
      disabledNodeKeys: [],
      isEditDataPermission: false,
    };
  },

  created() {
    this.loadGroupData();
  },

  methods: {
    loadGroupData() {
      getHmusergroupList().then((res) => {
        this.groupTree = treeToTree(res);
        if (this.expandedGroup.length === 0 && this.groupTree.length > 0) {
          this.expandedGroup = [this.groupTree[0].id];
        }
        if (!this.currentGroup.id && this.groupTree.length > 0) {
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.groupTree[0].id);
            this.handleGroupClick(this.groupTree[0]);
          });
        }
      });
    },

    handleGroupCommand(command, data) {
      console.log(command);
      console.log(data);
      if (command === "create") {
        this.handleGroupCreate(data);
      } else if (command === "up" || command === "down") {
        this.handleGroupMove(data, command);
      } else if (command === "edit") {
        this.handleGroupEdit(data);
      } else if (command === "delete") {
        this.handleGroupDelete(data);
      }
    },

    handleGroupCreate(data) {
      this.$refs.groupForm.addForm({
        parentId: data.id,
      });
    },

    handleGroupMove(data, command) {
      const request = command === "up" ? putHmusergroupUp : putHmusergroupDown;
      request({
        id: data.id,
      }).then(() => {
        this.loadGroupData();
      });
    },

    handleGroupExpand(data) {
      const { id } = data;
      this.expandedGroup.push(id);
    },
    handleGroupCollapse(data) {
      const { id } = data;
      this.expandedGroup = this.expandedGroup.filter((item) => item !== id);
    },

    handleGroupClick(data) {
      this.isEditDataPermission = false;
      this.currentGroup = data;
      this.loadGroupRole();
      this.loadGroupManager();
      this.loadGroupMember();
    },

    handleGroupEdit(data) {
      this.$refs.groupForm.editForm(data);
    },

    @Confirm({ message: i18n.t("sys.confirm_to_delete_user_group") })
    handleGroupDelete(data) {
      deleteHmusergroup([data.id]).then((res) => {
        // 如果删除的是当前用户组 需要重置当前值
        if (data.id === this.currentGroup.id) {
          this.currentGroup = {};
        }
        this.loadGroupData();
        this.$message.success(this.$t("sys.operation_success"));
      });
    },

    loadGroupRole() {
      getHmusergrouproleList({
        groupId: this.currentGroup.id,
      }).then((res) => {
        this.groupRoles = res;
      });
    },

    handleGroupRoleDelete(item) {
      deleteHmusergrouprole([item.id]).then((res) => {
        this.loadGroupRole();
        this.$message.success(this.$t("sys.operation_success"));
      });
    },

    handleGroupRoleAdd() {
      const groupId = this.$refs.tree.getCurrentKey();
      this.$refs.roleForm.addForm(
        {
          groupId,
        },
        {
          groupRoles: this.groupRoles.map((item) => item.roleId),
        }
      );
    },

    loadGroupUser(value) {
      if (value) {
        this.loadGroupMember();
      } else {
        this.loadGroupManager();
      }
    },

    loadGroupManager() {
      getHmusergroupmanageList({
        groupId: this.currentGroup.id,
      }).then((res) => {
        this.groupManagers = res;
      });
    },

    handleGroupManagerDelete(item) {
      deleteHmusergroupmanage({
        id: item.id,
      }).then((res) => {
        this.loadGroupManager();
        this.$message.success(this.$t("sys.operation_success"));
      });
    },

    handleGroupManagerAdd() {
      getHmorgListwithpermission().then((res) => {
        this.orgTree = arrayToTree(res);
        this.disabledNodeKeys = res
          .filter((i) => i.accessLevel === "ReadOnly")
          .map((i) => i.id);
        this.$refs.SelectManagerModal.open();
      });
    },

    handleManagerChange(data) {
      const { item } = data;
      const groupId = this.currentGroup.id;
      const user = item.map((ele) => ({
        groupId,
        userId: ele.id,
        isInsert: 0,
      }));
      postHmusergroupmanage(user).then((res) => {
        this.loadGroupManager();
        this.$message.success(this.$t("sys.operation_success"));
      });
    },

    handleSelectManagerNodeChange(org) {
      return getHmuserPageListwithpermission({
        pageSize: 100000,
        pageNo: 1,
        orgIds: org.id,
        status: 1,
      }).then((res) => {
        return res.data.map((item) => ({
          ...item,
          disabled:
            this.groupManagers.findIndex((m) => m.userId === item.id) > -1,
        }));
      });
    },

    loadGroupMember() {
      getHmusergroupmemberList({
        groupId: this.currentGroup.id,
      }).then((res) => {
        this.groupMembers = res;
      });
    },

    handleGroupMemberDelete(item) {
      deleteHmusergroupmember({
        id: item.id,
      }).then((res) => {
        this.loadGroupMember();
        this.$message.success(this.$t("sys.operation_success"));
      });
    },

    handleGroupMemberAdd() {
      getHmorgListwithpermission().then((res) => {
        const list = res.map((i) => ({
          ...i,
          disabled: i.accessLevel === "ReadOnly",
        }));
        this.orgTree = arrayToTree(list);
        this.$refs.SelectMemberModal.open();
      });
    },

    handleMemberChange(data) {
      const { node, item } = data;
      const groupId = this.currentGroup.id;
      const org = node.map((ele) => ({
        userGroupId: groupId,
        unionId: ele.id,
        isOrg: 1,
      }));
      const user = item.map((ele) => ({
        userGroupId: groupId,
        unionId: ele.id,
        isOrg: 0,
      }));
      postHmusergroupmember(org.concat(user)).then((res) => {
        this.loadGroupMember();
        this.$message.success(this.$t("sys.operation_success"));
      });
    },

    handleSelectMemberNodeChange(org) {
      return getHmuserPageListwithpermission({
        pageSize: 100000,
        pageNo: 1,
        orgIds: org.id,
        status: 1,
      }).then((res) => {
        return res.data.map((item) => ({
          ...item,
          disabled:
            this.groupMembers.findIndex(
              (m) => m.isOrg === 0 && m.unionId === item.id
            ) > -1,
        }));
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.setting-item {
  padding: 20px 0;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  min-height: 80px;

  .el-icon-plus {
    font-size: 18px;
    color: #409eff;
    font-weight: bold;
    cursor: pointer;
    position: relative;
    top: 3px;
  }
}

.role-name-tag {
  margin-top: 5px;
  margin-right: 10px;
  margin-bottom: 5px;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
  background-color: #409eff;
  //background-color: rgba(64,158,255, 0.85);
}
</style>
